﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;

namespace Zombie_Demo.Utilities
{
    public static class KeyboardWrapper
    {
        private static KeyboardState kbState; //The current state of the Keyboard
        private static Dictionary<Keys, KeysState> keysStates;

        /// <summary>
        /// Initialize the needed trackers
        /// </summary>
        public static void Init()
        {
            keysStates = new Dictionary<Keys, KeysState>();
        }

        /// <summary>
        /// Recieve all of the currently pressed keys
        /// </summary>
        public static Keys[] PressedKeys
        {
            get { return kbState.GetPressedKeys(); }
        }

        /// <summary>
        /// Get the current state of a given key
        /// </summary>
        /// <param name="k">The key to get</param>
        /// <returns>The KeysState of the requested Key</returns>
        public static KeysState GetKeyState(Keys k)
        {
            if (keysStates.ContainsKey(k))
                return keysStates[k];
            else
                return new KeysState();
        }

        public static bool IsPressed(Keys k)
        {
            return kbState.IsKeyDown(k);
        }

        /// <summary>
        /// Updates all the key presses and toggle times
        /// </summary>
        public static void Update()
        {
            kbState = Keyboard.GetState(); //Update the current Keybaord State

            List<Keys> down = kbState.GetPressedKeys().ToList(); //Get and set the list of pressed keys

            foreach (Keys k in down)
            {
                if (keysStates.ContainsKey(k))
                {
                    KeysState ks = keysStates[k];

                    if (ks.Pressed && !ks.WasPressed)
                        ks.WasPressed = true;

                    if (!ks.Pressed)
                    {
                        ks.Pressed = true;
                        ks.PressedTime = DateTime.Now;
                    }

                    keysStates[k] = ks;
                }
                else
                {
                    keysStates.Add(k, new KeysState(k, DateTime.Now, true, false));
                }
            }

            foreach (KeyValuePair<Keys, KeysState> pair in keysStates)
            {
                KeysState ks = pair.Value;

                if (!ks.Pressed && !down.Contains(pair.Key))
                    ks.WasPressed = false;

                if (ks.Pressed && !down.Contains(pair.Key))
                {
                    ks.Pressed = false;
                    ks.LengthOfPress = DateTime.Now - ks.PressedTime;
                }
            }
        }
    }
}
